<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/header.jsp" %>
<script src="${ctx}/assets/js/jquery.validate.js"></script>

<script type="text/javascript">
var butFlag=$("#operateType1").val();//用来判断当前页面是属于查看、新增、修改页面，从而判断点击取消按钮时的响应事件，查看：直接关闭
//定义一下时间插件
var scripts = [null, null];
$('.page-content-area').ace_ajax('loadScripts', scripts, function() {
	initButtons();
	$("#userIdDiv").hide();
});
	
	$.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
		_title: function(title) {
			var $title = this.options.title || '&nbsp;'
			if( ("title_html" in this.options) && this.options.title_html == true )
				title.html($title);
			else title.text($title);
		}
	}));
	/**
	 * 自定义菜单
	 */
	$("#privateMenus").dialog({
		hide:true,
		autoOpen:false,
		width:400,
		height:500,
		modal:true,
		//bgiframe:true,
		title: "<div class='widget-header'><h4 class='smaller'><i class='ace-icon fa fa-cog green'></i>&nbsp; 自定义角色菜单</h4></div>",
		title_html: true,
		
		buttons:[
	       {
		     id: "btnMSave",
		     html: "<i class='ace-icon fa fa-floppy-o bigger-110'></i>&nbsp; 确认","class" : "btn btn-success btn-minier",
		     click: function() {
			 save();
		      }
	       },
			{
				id: "btnMClose",
				html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; 关闭",
				"class" : "btn btn-minier",
				click: function() {
					$(this).dialog("close");
				}
			}]
});

//个人信息管理根据需要显示相应的按钮
function initButtons() {
	$("#btnPwdModify").hide();
	$("#btnPwdUpdate").hide();
	$("#btnModify").hide();
	$("#btnSave").hide();
	$("#btnCancle").hide();
	$("#btnClose").hide();
		if(butFlag=="queryDetail"){
			$("#btnPwdModify").show();
			$("#btnModify").show();
			$("#btnClose").show();
			disabled();	
	    }else{
			$("#btnSave").show();
			$("#btnClose").show();	
	    }
}
	
function disabled() {
		$("#privateUserForm input").attr("disabled", true);
		$("#privateUserForm select").attr("disabled", true);
		$("#privateUserForm textarea").attr("disabled", true);
	}

function enabled() {
		$("#privateUserForm input").attr("disabled", false);
		$("#privateUserForm select").attr("disabled", false);
		$("#privateUserForm textarea").attr("disabled", false);
	}
	
	//点击修改按钮后进行的操作
function modify(){
	enabled("privateUserForm");
	$("#relationStatus").attr("disabled",true);	
	 $("#tab1").find("input[type='checkBox']").each(function() { 
		$(this).attr("disabled", true); 
	});   
$("#btnPwdModify").hide();
$("#btnMenuModify").hide();
$("#btnSave").show();
$("#btnModify").hide();
$("#btnDelete").hide();
$("#btnCancle").show();
$("#btnClose").show();

$("#userCode").attr("disabled",true);
$("#userId").attr("disabled",true);
$("#showOrgId").attr("disabled",true);
$("#showDeptId").attr("disabled",true);
//$("#cardNo").attr("disabled",true);
$("#status").attr("disabled",true);
$("#createUser").attr("disabled",true);
$("#createTime").attr("disabled",true);
$("#updateUser").attr("disabled",true);
$("#updateTime").attr("disabled",true);
$("#privateUserForm input[type='checkbox']").attr("disabled", true);}

$("#privateUserForm").validate({
    errorElement: 'div',
    errorClass: 'help-block',
    focusInvalid: false,
    rules: {
       "userInfo.userName": {
          required: true
       },
       "userInfo.orgId": {
          required: true
       },
      /*  "userInfo.cardNo": {
	      required: true
	   }, */
	   "userInfo.userRoles": {
	      required: true
	   },
	   "userInfo.userCode":{
	   	  required: true
	   },
	   "userInfo.userStatus":{
	       required: true
	   },
	   "userInfo.status":{
	   	  required: true
	   }
    },
    messages: {
    	"userInfo.userName": {
           required: "用户名不能为空!"
        }, 
        "userInfo.orgId": {
           required: "所属机构不能为空!"
        }, 
       /*  "userInfo.cardNo": {
	       required: "证件号码不能为空!"
	    } ,  */
	    "userInfo.userRoles": {
		   required: "用户角色不能为空!"
		} , 
	    "userInfo.userCode":{
	       required: "用户编码不能为空！"
	    },
	    "userInfo.userStatus":{
	       required: "是否在职不能为空！"
	    },
	    "userInfo.status":{
		   required: "用户状态不能为空!"
		}
    },
    highlight: function (e) {
        $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
    },
    success: function (e) {
        $(e).closest('.form-group').removeClass('has-error').addClass('has-info');
        $(e).remove();
    },
    errorPlacement: function (error, element) {
        error.insertAfter(element.parent());
    }
});	
//保存操作
	function save(){
	//alert("保存操作");
	//校验privateUserForm表单
	  if ($("#privateUserForm").valid() == false) {
		 	alert("请检查表单是否正确填写~~");
	        return false;
	    } 
		enabled();			
		$.ajax({
			url : "${ctx}/user/updateUser.do",
			async : false,
			data : $("#privateUserForm").serialize(),
			type : "POST",
			dataType : "json",
			success: function(ret){	
				 if (ret.status == "ok") {
					 alert(ret.message);
					    $('#userDetailIframe').dialog("close");
				  } else{						  
					  alert(ret.message);
				  }	
			    },
			 error: function(ret){
				   alert(ret.responseText);
				   enabled();
			 }
		});	
		$("#updateInfoApply").load("${ctx}/user/toPrivateInfoApply.do?"+new Date().getTime());
}
//取消
function cancle(){
	if(butFlag=="insert"||butFlag=="queryDetail"||butFlag=="modifyPwd"){
		var s = "修改";
		if(butFlag=="insert"){
			s = '新增';
		}
		if(butFlag=="modifyPwd"){
			s="修改密码";
		}
		var flag = confirm("确认取消"+s+"吗？");
		if(flag){
			if(butFlag=="queryDetail"){
				//recoverData();
				document.privateUserForm.reset();
				$("#roleModifyInfo").html($("#roleModifyInfo").data("srcData"));
				disabled();
				initButtons();
			}
			if(butFlag=="insert"){
				$(this).dialog("close");
			}
			if(butFlag=="modifyPwd"){
				var userId=$("#user_Id").val();
				$('#userDetailIframe').load("${ctx}/user/toQueryDetail.do?userId="+userId+"&userFlag=1");
			}
		}
	}
}
//自定义菜单
function menuModify(){
	var userId =$("#userId").val();
	$("#privateMenus").show();
    $("#privateMenus").load("${ctx}/user/toUserMenuApply.do?userId="+userId);	
   	$("#privateMenus").dialog("open"); 
}
		 //机构树
	 function selectOrgDept(){
			 alert("1111111111");
		 var params = {"checkType":"dept"};
		 if(deptYn!="yes"){
			 params = {"checkType":"org","noVirtualOrg":"true"};
		 }
		 $("#deptIFrame").load("${ctx}/org/haveRootNodes.do",params);
		 $("#deptIFrame").dialog("open");
	 }
		//只允许输入数字  
		  function checkkey2(value,e){   
		        var key = window.event?e.keyCode:e.which;   
		        if( (key == 46) || (key > 95 && key < 106) || (key > 47 && key < 60)){   
		        }else if(key !=8){   
		            if (window.event) //IE   
		            {   
		                e.returnValue = false;   //event.returnValue=false 效果相同.   
		            }   
		            else //Firefox   
		            {   
		                e.preventDefault();   
		            }   
		        }   
		    }
		//用户Id验证
		function userIdVal(){
			var userId = $('#userId').val(); 
			if(userId=="")
				{
					alert("用户编号不能为空！");
				}
			var params = {"userInfo.userId":$('#userId').val()};
			$.post("${ctx}/user/userIdVal.do",params,
					function(message){
					    if(message == "1") {
					    	var flag = confirm("已存在该用户编号,是否引用该用户信息？");
							if(flag){
								$.post("${ctx}/user/selectUserInfoByUserId.do",params,
										function(userInfo){
									   	//json赋值
										var json=$.parseJSON(userInfo);
										writeJson(json);
								}
							    );
							}
					    }
					  }	
		    );
		}
		//验证是否可选择任职状态
		function relationStatusVal(){
			if($('#status').val()==""){
				alert('请先选择用户状态！');
			}
		}
		//验证是否可选择不是"未启动"的任职状态
		function relationStatusVal2(){
			if($('#status').val()=="0" && ($('#relationStatus').val()!="0" && $('#relationStatus').val()!="")){
				alert('由于用户状态为未启用，任职状态只能选择未启用！');
				 $('#relationStatus').val("");
			}
		}
		//身份证校验
		/* function cardIdVal(){
			if($('#cardType').val()=='01'){
				var cardNo = $('#cardNo').val();
				return isChinaIdNo(cardNo);
			}else{
				return true;				
			}
		} */
     	 //画option
		 function writeOption(){
			 $("#defaultRole").find("option").remove();
			 var userRoles = document.getElementsByName('userRoles');			 
			 var roleNames = document.getElementsByName('roleNames');
			    var str = ""; 
			    var dr = $("#defaultRole1").val();			    
			    for(var i=0;i<userRoles.length;i++){
			    		 if(userRoles[i].checked){  
						    	if(userRoles[i].value == dr){
						    		str+="<option value='"+userRoles[i].value+"' selected='selected'>" + roleNames[i].value + "</option>";
						    	}else{
						    		str+="<option value='"+userRoles[i].value+"'>" + roleNames[i].value + "</option>";
						    	}
						    		
						    } 			    					    		
				    
			    }
			    $("#defaultRole").append(str);
		 }
     	//限制长度
     	function lenVal(o,maxLen){  
     		checkTextArea(o,maxLen);
     		o.value=o.value.substring(0,maxLen/2);

     	}
		//去掉首尾空格
		function LTrim(str){   
			var i;    
			for(i=0;i<str.length;i++){        
				if(str.charAt(i)!=" "&&str.charAt(i)!=" ")
					break;    
				}    
			str=str.substring(i,str.length);    
			return str;
			}
		function RTrim(str){    
				var i;    
				for(i=str.length-1;i>=0;i--){        
					if(str.charAt(i)!=" "&&str.charAt(i)!=" ")
						break;    
					}    
				str=str.substring(0,i+1);    
				return str;
				}
		function Trim(str){
			return LTrim(RTrim(str));
			}
		//去掉首尾空格后返回
		function getTrim(o){
			o.value=Trim(o.value);
			validateAlias();
		}
		function validateAlias(){
			var userName = $("#userName").val();
			if(userName==''){
				return false;
			}
			var params = {"userInfo.userName":userName, "userInfo.userId":$("#userId").val()};
			$.post("${ctx}/user/validateUserName.do",params,
					function(message){
					    if(message == "1") {
					    	alert("该用户名已经被占用，请换一个，如加上数字");
					    	return false;
					    }else{
					    	return true;
					    }
					  }	
			   );
			return true;
		}
		
		function modifyPwd(){
		$("#btnPwdModify").hide();
		$("#btnPwdUpdate").show();
		$("#btnModify").hide();
		$("#btnSave").hide();
		$("#btnDelete").hide();
		$("#btnCancle").show();
		$("#btnClose").show();	
		$("#btnMenuModify").hide();
		}
		
		function pwdModify(){
			modifyPwd();
			var userId=$("#userId").val();
			$("#userDetailIframe").load("${ctx}/user/toUpdatePwd.do?userId="+userId);
		}

		//根据选中的角色生成下拉列表
		function sele() {
			$(".roleIdstatus").each(function(){
				if(!$(this).attr('checked')){
					$(this).attr('disabled');
				}
			});
		}

	</script>
	
	<div id="tab1" class="row">
	<div class="col-xs-12">	
	<form id = "privateUserForm" name = "privateUserForm" class="form-horizontal" role="form">
	        <input type="hidden" id="defaultRole1" value="${defaultRole}">
			<input type="hidden" id="resetBut" name="resetBut" value="${resetBut}">			
			<input type="hidden" id="operateType1" name="operateType" value="${operateType}">
			<input type="hidden" id="userIdAuto" name="userIdAuto" value="${userIdAuto}">


      	  <div class="form-group" id="userIdDiv">
					<label class="col-sm-4 control-label no-padding-right" for="userId">用户ID：<font color="red">*</font></label>
					
					<div class="col-sm-8">	
						   <div class="grid_4"><input type="text" class="col-xs-10 col-sm-8"  id="userId" title="用户编号由系统自动生成" name="userInfo.userId" value="${userInfo.userId}" maxlength="8" readonly/></div>
																		
					</div>
		  </div>
		  
		  <div class="form-group">
                    <label class="col-sm-4 control-label no-padding-right" for="userCode">用户编码：<font color="red">*</font></label>
                    <div class="col-sm-8">
                      <div class="clearfix">
                           <input type="text" class="col-xs-10 col-sm-8 form-txt "  id="userCode" placeholder="请输入用户编码" name="userInfo.userCode" value="${userInfo.userCode}" readonly/>
                      </div>
                    </div>
          </div>
		  
		  <div class="form-group">
					<label class="col-sm-4 control-label no-padding-right" for="userName">用户名：<font color="red">*</font></label>
					<div class="col-sm-8">
					  <div class="clearfix">
					       <input type="text" class="col-xs-10 col-sm-8 form-txt {required:true,messages:{required:'请输入用户名'}}"  id="userName"  name="userInfo.userName" value="${userInfo.userName}" maxlength="9" />
					  </div>
					</div>
		  </div>

		  
		  <div class="form-group">
					<label class="col-sm-4 control-label no-padding-right" for="gender">性别：</label>
					<div class="col-sm-8">
					    <select class="col-xs-10 col-sm-8" id="gender" name="userInfo.gender">
						    <hw:dictOption dictType="D00003"  value="${userInfo.gender}" nullLable="no"/>
						</select>
					</div>
		  </div>
		 <%--  <div class="form-group">
                    <label class="col-sm-4 control-label no-padding-right" for="cardNo">身份证号码：<font color="red">*</font></label>
                    <div class="col-sm-8">
                        <div class="clearfix">
                           <input type="text" class="col-xs-10 col-sm-8 form-txt"  id="cardNo"  name="userInfo.cardNo" value="${userInfo.cardNo}" />
                           <input type="hidden" id="cardType" name="cardType" value="01">
                        </div>
                    </div>
          </div> --%>
		  <div class="form-group">
					<label class="col-sm-4 control-label no-padding-right" for="orgId">所属机构：<font color="red">*</font></label>
					<div class="col-sm-8">
				    	<div class="clearfix">
					       <input type="text" class="col-xs-10 col-sm-8"  id="showOrgId"  name=""  title="新建用户成功后，用户的所属机构和部门将不能修改！" value='<hw:orgName orgId="${userInfo.orgId}"/>' />
					       <input type="hidden" class="col-xs-10 col-sm-8"  id="orgId"  name="userInfo.orgId" title="新建用户成功后，用户的所属机构和部门将不能修改！" value="${userInfo.orgId}" />
					    </div>
					</div>
		  </div>
          <div class="form-group">
                    <label class="col-sm-4 control-label no-padding-right" for="userStatus">是否在职：<font color="red">*</font></label>
                    <div class="col-sm-8">
                    	<div class="clearfix">
                           <select class="col-xs-10 col-sm-8" id="form-field-select-11" data-placeholder="是否在职" name="userInfo.userStatus">
							 	<hw:dictOption dictType="D00051" value="${userInfo.userStatus}"/>
						   </select>
                        </div>
                    </div>
          </div>
          <div class="form-group">
                    <label class="col-sm-4 control-label no-padding-right" for="status">用户状态：<font color="red">*</font></label>
                    <div class="col-sm-8">
                        <select class="col-xs-10 col-sm-8" id="status" name="userInfo.status">
                            <hw:dictOption dictType="D00026" value="${userInfo.status}" defaultValue="1"/>
                         </select>
                    </div>
          </div>
         
		 <div class="form-group">
                    <label class="col-sm-4 control-label no-padding-right" for="userRoles">角色：<font color="red">*</font></label>
                    <div class="col-sm-8">
                       <div class="clearfix">				     
                        
                         <div class="checkbox" id="roleModifyInfo">
                           	  <c:forEach items="${userInfo.roles}" var="role" varStatus="i">	
	                               <label>
	                                  <input type="checkBox" class="ace roleIdstatus" name="roles[${i.index }].roleId" id="userRoles" value="${role.roleId}" onchange="sel();"  checked="checked" /> <span class="lbl">${role.roleName}</span>
	                                  <%-- <input type="hidden" id="roleNames" name="roles[${i.index }].roleName" value="${role.roleName}">	 --%>
	                               </label>	
                              </c:forEach>
                              
                        </div>
  						
  						</div>
                    </div>
	</form>
	</div>
	</div>
  <div id="deptIFrame"></div>
  <div id="privateMenus"></div>
